# main imports
import sys
import os
import xbmc
import xbmcgui
import xbmcplugin

import urllib
import urllib2
import re

from MediaWindow import MediaWindow, DirectoryItem

class xbPlugin:
    def __init__( self ):
        self._get_settings()
        sortmethods = ( xbmcplugin.SORT_METHOD_LABEL, )
        self.MediaWindow = MediaWindow( int( sys.argv[ 1 ] ), category=self.PluginCategory, content="tvshows", sortmethods=sortmethods, fanart=( self.settings[ "fanart_image" ], self.Fanart, ) )

    def ChannelList ( self ):
        self.MediaWindow.end( self.get_channellisting() )

    def Channel ( self, ChannelName, ChannelID ):
        self.MediaWindow.end( self.get_serieslisting(ChannelName, ChannelID) )        

    def Series( self, Channel, SeriesName, SeriesID, Season ):
        xbmcplugin.setContent( handle=int( sys.argv[ 1 ] ), content="episodes" )
        xbmcplugin.addSortMethod( int( sys.argv[ 1 ] ), xbmcplugin.SORT_METHOD_EPISODE )
        
        self.MediaWindow.end( self.get_seasonlisting(Channel, SeriesName, SeriesID, Season) )        

    def _get_settings( self ):
        self.settings = {}
        self.PluginCategory = 'VOD' 
        self.settings[ "fanart_image" ] = ''
        self.Fanart = ''

    def get_channellisting(self):
        req = urllib2.Request('http://api.thevoddb.org/service/channels.asmx/list')
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        source=response.read()
        response.close()        
        matches=re.compile('<Channel>(.*?)</Channel>', re.DOTALL).findall(source)
        for match in matches:
            channelid = re.compile('<ID>(.*?)</ID>', re.DOTALL).findall(match)[0]            
            name = re.compile('<Name>(.*?)</Name>', re.DOTALL).findall(match)[0]
            thumb = re.compile('<Thumbnail>(.*?)</Thumbnail>', re.DOTALL).findall(match)[0]            
            chiltcount = int(re.compile('<ChildCount>(.*?)</ChildCount>', re.DOTALL).findall(match)[0])
            self.addChannel(name, channelid, thumb, chiltcount, '')

        return True

    def get_serieslisting(self, ChannelName, ChannelID):
        req = urllib2.Request('http://api.thevoddb.org/service/series.asmx/list?ChannelID=' + str(ChannelID))
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        source=response.read()
        response.close()
        matches=re.compile('<Series>(.*?)</Series>', re.DOTALL).findall(source)
        for match in matches:
            seriesid = re.compile('<ID>(.*?)</ID>', re.DOTALL).findall(match)[0]
            name = re.compile('<Name>(.*?)</Name>', re.DOTALL).findall(match)[0]
            try:
                overview = re.compile('<Overview>(.*?)</Overview>', re.DOTALL).findall(match)[0]
            except:
                overview = ""
            try:
                thumb = re.compile('<Thumbnail>(.*?)</Thumbnail>', re.DOTALL).findall(match)[0]
            except:
                thumb = ''
            chiltcount = int(re.compile('<ChildCount>(.*?)</ChildCount>', re.DOTALL).findall(match)[0])
            self.addShow(ChannelName, name, seriesid, thumb, chiltcount, overview)

        return True

    def get_seasonlisting(self, Channel, SeriesName, SeriesID, Season):
        if (Season == '-1'):
            req = urllib2.Request('http://api.thevoddb.org/service/seasons.asmx/list?SeriesID=' + str(SeriesID))
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
            response = urllib2.urlopen(req)
            source=response.read()
            response.close()
            matches=re.compile('<Season>(.*?)</Season>', re.DOTALL).findall(source)
            for match in matches:
                seasonid = re.compile('<ID>(.*?)</ID>', re.DOTALL).findall(match)[0]
                title = re.compile('<Title>(.*?)</Title>', re.DOTALL).findall(match)[0]
                number = re.compile('<Number>(.*?)</Number>', re.DOTALL).findall(match)[0]
                try:
                    thumb = re.compile('<Thumb>(.*?)</Thumb>', re.DOTALL).findall(match)[0]
                except:
                    thumb = ""
                chiltcount = int(re.compile('<ChildCount>(.*?)</ChildCount>', re.DOTALL).findall(match)[0])
                self.addSeason(Channel, SeriesName, SeriesID, seasonid, title, 'mako.jpg', chiltcount, '')
        else:
            req = urllib2.Request('http://api.thevoddb.org/service/episodes.asmx/list?SeriesID=' + str(SeriesID) + '&SeasonID=' + str(Season))
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
            response = urllib2.urlopen(req)
            source=response.read()
            response.close()
            matches=re.compile('<Episode>(.*?)</Episode>', re.DOTALL).findall(source)
            for match in matches:
                episodeid = re.compile('<ID>(.*?)</ID>', re.DOTALL).findall(match)[0]
                SeasonIndex = re.compile('<SeasonIndex>(.*?)</SeasonIndex>', re.DOTALL).findall(match)[0]                
                title = re.compile('<Title>(.*?)</Title>', re.DOTALL).findall(match)[0]
                number = re.compile('<Number>(.*?)</Number>', re.DOTALL).findall(match)[0]
                try:
                    overview = re.compile('<Overview>(.*?)</Overview>', re.DOTALL).findall(match)[0]
                except:
                    overview = ""
                try:
                    thumb = re.compile('<Thumb>(.*?)</Thumb>', re.DOTALL).findall(match)[0]
                except:
                    thumb = ""
                try:
                    _shortoverview = re.compile('<ShortOverview>(.*?)</ShortOverview>', re.DOTALL).findall(match)[0]
                except:
                    _shortoverview = ""
                try:
                    _Year = re.compile('<Year>(.*?)</Year>', re.DOTALL).findall(match)[0]
                except:
                    _Year = ""
                if _Year == '':
                    _Year = 1900
                else:
                    _Year = int(Year)
                try:
                    _Rating = re.compile('<Rating>(.*?)</Rating>', re.DOTALL).findall(match)[0]
                except:
                    _Rating = 0
                if _Rating == '':
                    _Rating = 0
                else:
                    _Rating = float(_Rating)                
                try:
                    _PlayCount = re.compile('<PlayCount>(.*?)</PlayCount>', re.DOTALL).findall(match)[0]
                except:
                    _PlayCount = ""
                if _PlayCount == '':
                    _PlayCount = 0
                else:
                    _PlayCount = int(_PlayCount)                    
                try:
                    _MPAA = re.compile('<MPAA>(.*?)</MPAA>', re.DOTALL).findall(match)[0]
                except:
                    _MPAA = ""
                try:
                    _Duration = re.compile('<Duration>(.*?)</Duration>', re.DOTALL).findall(match)[0]
                except:
                    _Duration = ""
                try:
                    _Studio = re.compile('<Studio>(.*?)</Studio>', re.DOTALL).findall(match)[0]
                except:
                    _Studio = ""
                try:
                    _Tagline = re.compile('<Tagline>(.*?)</Tagline>', re.DOTALL).findall(match)[0]
                except:
                    _Tagline = ""
                try:
                    _Aired = re.compile('<Aired>(.*?)</Aired>', re.DOTALL).findall(match)[0]
                except:
                    _Aired = ""
                try:
                    _Trailer = re.compile('<Trailer>(.*?)</Trailer>', re.DOTALL).findall(match)[0]
                except:
                    _Trailer = ""

                feed = re.compile('<Feed>(.*?)</Feed>', re.DOTALL).findall(match)[0]
                self.addEpisode(title, feed, thumb, overview, tvshowtitle=SeriesName, SeasonIndex=int(SeasonIndex), EpisodeIndex=int(number), plotoutline=_shortoverview, Year=_Year, Rating=_Rating, PlayCount=_PlayCount, MPAA=_MPAA, Duration=_Duration, Studio=_Studio, Tagline=_Tagline, Aired=_Aired, Trailer=_Trailer)
        return True

    def addChannel(self, ChannelName, ChannelID, iconimage, childcount, plot=""):
        u = sys.argv[0] + "?ChannelName=" + urllib.quote_plus(ChannelName) + "&ChannelID=" + str(ChannelID)
        ok = True
        #iconimage = iconimage.replace('&amp;', '&')        
        liz = xbmcgui.ListItem(label=ChannelName, label2=ChannelID, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "tvshowtitle": ChannelName , "plot": plot } )
        ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True, totalItems=childcount)
        return ok

    def addShow(self, Channel, SeriesName, SeriesID, iconimage, childcount, plot=""):
        u = sys.argv[0] + "?Channel=" + urllib.quote_plus(Channel) + "&SeriesName=" + urllib.quote_plus(SeriesName) + "&SeriesID=" + str(SeriesID) + "&Season=-1"
        ok = True
        if (iconimage == 'http://img.mako.co.ilnull'):
            iconimage = ""
        #iconimage = iconimage.replace('&amp;', '&')            
        liz = xbmcgui.ListItem(label=SeriesName, label2=SeriesID, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "tvshowtitle": SeriesName , "plot": plot } )
        ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True, totalItems=childcount)
        return ok

    def addSeason(self, Channel, SeriesName, SeriesID, seasonid, title, iconimage, childcount, plot):
        u = sys.argv[0] + "?Channel=" + urllib.quote_plus(Channel) + "&SeriesName=" + urllib.quote_plus(SeriesName) + "&SeriesID=" + str(SeriesID) + "&Season=" + str(seasonid)
        ok=True
        #iconimage = iconimage.replace('&amp;', '&')        
        liz=xbmcgui.ListItem(label=title, label2=seasonid, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "tvshowtitle": title } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True,totalItems=childcount)
        return ok

    def addEpisode(self, title, url, thumbnailimage, plot, Year=1900, genre="", EpisodeIndex=1, SeasonIndex=1, title2="", Rating=0, cast="", castandrole="", director="", MPAA="", plotoutline="", Duration="", Studio="", Tagline="", writer="", tvshowtitle="", premiered="", status="", code="", Aired="", creditsto="", Trailer="", PlayCount=0):
        url = url.replace('&amp;', '&')
        thumbnailimage = thumbnailimage.replace('&amp;', '&')
        litem = xbmcgui.ListItem(title, title2, iconImage= thumbnailimage, thumbnailImage= thumbnailimage)
        litem.setInfo( type= "Video", infoLabels= { "title": title , "plot": plot , "year": Year , "genre" : genre, "episode" : EpisodeIndex, "season": SeasonIndex, "rating": Rating, "cast": cast, "castandrole": castandrole, "director": director, "mpaa": MPAA, "plotoutline": plotoutline, "duration": Duration, "studio": Studio, "tagline": Tagline, "writer": writer, "tvshowtitle": tvshowtitle, "premiered": premiered, "status": status, "code": code, "aired": Aired, "credits": creditsto, "trailer": Trailer, "playcount": PlayCount} )
        return xbmcplugin.addDirectoryItem( handle= int(sys.argv[1]), url= url, listitem=litem )

